﻿Imports System.Text
Imports ConfigurationManager
Imports System.IO
Imports System.Net
Imports System.Web
Imports System.Web.Script.Serialization
Imports System.Threading
Imports System.Xml.Serialization

Public Class frmMain
#Region ">> Declares"
    Dim SessionID As String = String.Empty
    Dim bDecrypted As String = String.Empty
    Dim jsonSerializer As New JavaScriptSerializer
    Dim MainJSON As Dictionary(Of String, Object)
    Dim cCook As New Net.CookieContainer
    Dim hangID As Integer
    Dim Helper As Helper
    Dim Hangars As New List(Of Structures.Hangar)
    Dim Logger As New Logger(Me)

    Dim SavedData As List(Of SavedData)
#End Region

#Region ">> Login"
    Private Sub cmdLogin_Click(sender As Object, e As EventArgs) Handles cmdLogin.Click
        If txtPassword.Text.Trim = "" OrElse txtUsername.Text.Trim = "" OrElse txtServer.Text.Trim = "" Then
            MessageBox.Show("Please fill out all fields!")
        Else

            txtUsername.Enabled = False
            txtServer.Enabled = False
            cmdDelete.Enabled = False
            chkSaveData.Enabled = False
            txtPassword.Enabled = False
            cmdLogin.Enabled = False

            cmbHangars.Enabled = False
            cmbHangars.Items.Clear()
            cmdLogToHangar.Enabled = False
            cmdChangeConfiguration.Enabled = False
            cmdOpenWebbrowser.Enabled = False
            cmdSaveConfiguration.Enabled = False
            With New Thread(AddressOf DoLogin)
                .IsBackground = True
                .Start()
            End With
        End If

    End Sub

    Sub DoLogin()
        Dim user = "", pass = "", server = ""
        Invoke(Sub()
                   user = System.Web.HttpUtility.UrlEncode(txtUsername.Text)
                   pass = System.Web.HttpUtility.UrlEncode(txtPassword.Text)
                   server = System.Web.HttpUtility.UrlEncode(txtServer.Text)
               End Sub)
        If Login(user, pass, server) = True Then
            Invoke(Sub() gbLogin.Enabled = True)
            Invoke(Sub()
                       If chkSaveData.Checked Then
                           If Not My.Settings.Settings.Contains(txtUsername.Text & ":" & txtPassword.Text & ":" & txtServer.Text) Then
                               My.Settings.Settings.Add(txtUsername.Text & ":" & txtPassword.Text & ":" & txtServer.Text)
                               My.Settings.Save()
                           End If
                       End If

                       chkSaveData.Enabled = False
                       txtUsername.Enabled = False
                       txtServer.Enabled = False
                       txtPassword.Enabled = False
                       cmdDelete.Enabled = False
                       cmdLogin.Enabled = True
                       cmdOpenWebbrowser.Enabled = True
                       cmdLogin.Text = "Relog"
                       Me.Text &= " | Logged in as " & txtUsername.Text
                       Logger.Log("Successfully logged in! Loading hangars...")
                       Me.Refresh()
                   End Sub)
            bDecrypted = Crypter.Decode(WebRPOST("http://" & txtServer.Text & ".darkorbit.bigpoint.com/flashAPI/inventory.php", "params=" & Crypter.Encode("{" & Chr(34) & "nr" & Chr(34) & ":1}") & "&action=init", cCook))
            MainJSON = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(bDecrypted)
            If CStr(MainJSON.Item("isError")) <> "0" Then
                MsgBox("Error from darkorbit: " & MainJSON.Item("error").Item("message"))
                Application.Exit()
            End If
            Helper = New Helper(MainJSON)
            For Each hangar In MainJSON.Item("data").Item("ret").Item("hangars")
                Invoke(Sub() cmbHangars.Items.Add(hangar.Item("hangarID") & "(" & Helper.ParseExactName(hangar.Item("general").Item("ship").Item("SM")) & ")"))
            Next
            Invoke(Sub() cmbHangars.SelectedIndex = 0)
            Invoke(Sub()
                       cmbHangars.Enabled = True
                       cmdLogToHangar.Enabled = True
                       Logger.Log("Done!")
                   End Sub)
        Else
            MessageBox.Show("Failed to login!")
            Invoke(Sub()
                       Logger.Log("Failed to login! Please check your data!")
                       cmbHangars.Enabled = False
                       cmdChangeConfiguration.Enabled = False
                       cmdSaveConfiguration.Enabled = False
                       cmdLogToHangar.Enabled = False
                       cmdDelete.Enabled = True
                       cmdOpenWebbrowser.Enabled = False
                       chkSaveData.Enabled = True
                       txtUsername.Enabled = True
                       txtServer.Enabled = True
                       txtPassword.Enabled = True
                       cmdLogin.Enabled = True
                   End Sub)
        End If
    End Sub

    Function Login(ByVal sUsername As String, ByVal sPassword As String, ByVal sServer As String) As Boolean
        Try
            Dim sb As StringBuilder = New StringBuilder()
            sb.Append("loginForm_default_username=")
            sb.Append(sUsername)
            sb.Append("&loginForm_default_password=")
            sb.Append(sPassword)
            sb.Append("&loginForm_default_login_submit=Login")


            Dim sLogged As String = WebRPOST("http://www.darkorbit.com/?locale=us&aid=0", sb.ToString, cCook)

            Dim str As String() = sLogged.Split("<"c)

            For i As Integer = 0 To str.Count - 1
                If str(i).Contains("http://" & sServer & ".darkorbit.bigpoint.com/GameAPI.php?") Then
                    Dim url As String = GetBetween(str(i), "target=""", Chr(34))
                    cCook = New CookieContainer
                    Dim second As String = WebRGET(url, cCook)
                    If second.Trim() = "" Then
                        Return False
                    End If
                    Return second.Contains(sUsername)
                End If
            Next
            Return False
        Catch ex As Exception
            Return False
        End Try
    End Function
#End Region

#Region ">> HTTP"

    Public Function WebRPOST(ByVal sUrl As String, ByVal sPost As String, ByVal cookies As CookieContainer) As String
        Try
            Dim nRequest As HttpWebRequest = CType(WebRequest.Create(sUrl), HttpWebRequest)
            nRequest.Method = "POST"
            nRequest.CookieContainer = cookies
            nRequest.ContentType = "application/x-www-form-urlencoded"
            Dim nbyteArray() As Byte = Encoding.Default.GetBytes(sPost)
            nRequest.ContentLength = nbyteArray.Length
            Dim nDataStream As Stream = nRequest.GetRequestStream()
            nDataStream.Write(nbyteArray, 0, nbyteArray.Length)
            nDataStream.Close()
            nRequest.KeepAlive = True
            nRequest.AllowAutoRedirect = True
            nRequest.PreAuthenticate = True

            Dim nResponse As HttpWebResponse = CType(nRequest.GetResponse(), HttpWebResponse)
            nDataStream = nResponse.GetResponseStream()
            Dim nreader As New StreamReader(nDataStream)
            Dim nServerResponse As String = nreader.ReadToEnd()
            nreader.Close()
            nDataStream.Close()
            nResponse.Close()

            Return nServerResponse
        Catch ex As Exception
            Return ""
        End Try

    End Function

    Public Function WebRGET(ByVal sUrl As String, Optional ByRef cookies As CookieContainer = Nothing) As String
        Try
            Dim Request As HttpWebRequest = CType(WebRequest.Create(sUrl), HttpWebRequest)
            Request.Method = "GET"
            Request.CookieContainer = cookies
            Request.ContentType = "application/x-www-form-urlencoded"
            Request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials


            Dim Response As HttpWebResponse = CType(Request.GetResponse(), HttpWebResponse)
            Dim DataStream = Response.GetResponseStream()
            Dim reader As New StreamReader(DataStream)
            Dim ServerResponse As String = reader.ReadToEnd()
            reader.Close()
            DataStream.Close()
            Response.Close()

            Return ServerResponse
        Catch ex As Exception
            Return ""
        End Try


    End Function

    Public Function GetBetween(ByRef strSource As String, ByRef strStart As String, ByRef strEnd As String, Optional ByRef startPos As Integer = 0) As String
        Try
            Dim iPos As Integer, iEnd As Integer, lenStart As Integer = strStart.Length
            Dim strResult As String
            strResult = String.Empty
            iPos = strSource.IndexOf(strStart, startPos)
            iEnd = strSource.IndexOf(strEnd, iPos + lenStart)
            If iPos <> -1 AndAlso iEnd <> -1 Then
                strResult = strSource.Substring(iPos + lenStart, iEnd - (iPos + lenStart))
            End If
            Return strResult
        Catch
            Return ""
        End Try
    End Function

#End Region

#Region ">> Display Items"
    Private Sub cmdLogToHangar_Click(sender As Object, e As EventArgs) Handles cmdLogToHangar.Click
        cmbHangars.Enabled = False
        cmdLogToHangar.Enabled = False
        cmdSaveConfiguration.Enabled = False
        cmdChangeConfiguration.Enabled = False
        Hangars.Clear()
        With New Thread(AddressOf DoLoginToHangar)
            .IsBackground = True
            .Start()
        End With
    End Sub

    Sub DoLoginToHangar()
        Logger.Log("Login to hangar...")
        Me.Invoke(Sub()
                      tvHangar.Nodes.Clear()
                      Application.DoEvents()
                      Me.Invalidate()
                  End Sub)
        Dim index As Integer
        Invoke(Sub() index = cmbHangars.SelectedIndex + 1)

        bDecrypted = Crypter.Decode(WebRPOST("http://" & txtServer.Text & ".darkorbit.bigpoint.com/flashAPI/inventory.php", "params=" & Crypter.Encode("{" & Chr(34) & "nr" & Chr(34) & ":" & index & "}") & "&action=init", cCook))
        MainJSON = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(bDecrypted)
        If CStr(MainJSON.Item("isError")) <> "0" Then
            MsgBox("Failed to login!")
            Invoke(Sub()
                       cmbHangars.Enabled = True
                       cmdLogToHangar.Enabled = True
                       cmdChangeConfiguration.Enabled = True
                   End Sub)
            Exit Sub
        End If
        hangID = MainJSON.Item("data").Item("ret").Item("hangars")(index - 1).Item("hangarID")
        Me.Invoke(Sub()
                      LoadEquipmentTV()
                      LoadHangarTV()
                      cmdSaveConfiguration.Enabled = True
                      cmbHangars.Enabled = True
                      cmdLogToHangar.Enabled = True
                      cmdChangeConfiguration.Enabled = True
                  End Sub)
    End Sub

    Sub LoadEquipmentTV()
        Dim items As List(Of String()) = New List(Of String())
        '0 Name
        'resIds(":")
        'Count
        Logger.Log("Loading equipment...")
        For Each item In MainJSON.Item("data").item("ret").item("items")
            Dim resId As String = item.Item("I")
            Dim Name As String = Helper.GetNameByResourceID(item.Item("I"))
            Dim canAdd As Boolean = True

            For i2 = 0 To items.Count - 1

                If items(i2)(0) = Name Then
                    items(i2)(1) &= resId & ":"
                    items(i2)(2) = CStr(CInt(items(i2)(2)) + 1)
                    canAdd = False
                End If

            Next
            If canAdd Then
                items.Add({Name, resId & ":", "1"})
            End If
        Next
        With tvHangar.Nodes.Add("Equipment Items")
            For Each item In items
                If Helper.IsValidConfigType(Helper.GetTypeByResourceID(CInt(item(1).Split(CChar(":"))(0)))) Then
                    With .Nodes.Add(item(0) & " (" & item(2) & ")")
                        For Each member In item(1).Split(":"c)
                            If member.Trim() <> "" Then
                                .Nodes.Add(member)
                            End If
                        Next
                    End With
                End If
            Next
        End With
        Logger.Log("Done!")
    End Sub

    Sub LoadHangarTV()
        Logger.Log("Loading hangars...")

        '
        '  Hangars
        '


        Dim ship As New Structures.Ship
        For Each item In MainJSON.Item("data").Item("ret").Item("hangars")
            If item.Item("hangarID").ToString = hangID Then
                With ship
                    .Level = item.Item("general").Item("ship").Item("I")
                    .HitPoints = item.Item("general").Item("ship").Item("HP")
                    .L = item.Item("general").Item("ship").Item("L")
                    .SM = item.Item("general").Item("ship").Item("SM")
                    .avaibleDesings = New List(Of String)
                    For Each desing In item.Item("general").Item("ship").Item("M")
                        .avaibleDesings.Add(desing.ToString)
                    Next
                End With

                Dim lockedinfos As New Structures.PETLockedItems
                With lockedinfos
                    If CBool(item.Item("general").ContainsKey("pet")) Then
                        .Lasers = item.Item("general").Item("pet").Item("lockedSlots").Item("lasers")
                        .Generators = item.Item("general").Item("pet").Item("lockedSlots").Item("generators")
                        .Gears = item.Item("general").Item("pet").Item("lockedSlots").Item("gears")
                        .Protocols = item.Item("general").Item("pet").Item("lockedSlots").Item("protocols")
                    End If
                End With
                Dim pet As New Structures.PET
                With pet
                    If item.Item("general").ContainsKey("pet") Then
                        .PETID = item.Item("general").Item("pet").Item("I")
                        .HP = item.Item("general").Item("pet").Item("HP")
                        .Level = item.Item("general").Item("pet").Item("LV")
                        .Name = item.Item("general").Item("pet").Item("PN")
                        .L = item.Item("general").Item("pet").Item("L")
                        .LockedItems = lockedinfos
                    End If
                End With

                Dim drones As New Structures.Drones
                With drones
                    .Drones = New List(Of Structures.SingleDrone)
                    If item.Item("general").ContainsKey("drones") Then
                        For Each itm In item.Item("general").Item("drones")
                            Dim drone As New Structures.SingleDrone
                            With drone
                                .ID = itm.Item("I")
                                .L = itm.Item("L")
                                .LV = itm.Item("LV")
                                .HPPercent = itm.Item("HP")
                                .EFPercent = itm.Item("EF")
                                .SP = itm.Item("SP")
                                .DE = itm.Item("DE")
                                .DL = itm.Item("DL")
                                .SL = itm.Item("SL")
                                drones.Drones.Add(drone)
                            End With
                        Next
                    End If
                    drones.Count = drones.Drones.Count
                End With

                Dim hangar As New Structures.Hangar
                With hangar
                    .Ship = ship
                    .PET = pet
                    .Drones = drones
                    .HangarID = item.Item("hangarID")
                    .HangarName = item.Item("name")
                    .isActive = DirectCast(item.Item("hangar_is_active"), Boolean)
                    .isSelected = DirectCast(item.Item("hangar_is_selected"), Boolean)
                End With
                Hangars.Add(hangar)
            End If
        Next

        With tvHangar.Nodes.Add("Hangars")
            For Each item In Hangars
                With .Nodes.Add("HangarID: " & item.HangarID)
                    With .Nodes.Add("General")
                        With .Nodes.Add("Ship: " & Helper.GetNameByL(item.Ship.L))
                            .Nodes.Add("HP: " & item.Ship.HitPoints)
                            .Nodes.Add("Selected Design: " & Helper.ParseExactName(item.Ship.SM))
                            With .Nodes.Add("Avaible Designs")
                                For Each des In item.Ship.avaibleDesings
                                    .Nodes.Add(Helper.ParseExactName(des))
                                Next
                            End With

                        End With
                        With .Nodes.Add("Drones: " & item.Drones.Count)
                            For Each drn In item.Drones.Drones
                                With .Nodes.Add(Helper.GetNameByL(drn.L))
                                    .Nodes.Add("Efficiency[Damage/Shield]: " & drn.EFPercent)
                                    .Nodes.Add("ID: " & drn.ID)
                                    .Nodes.Add("Damage Level: " & drn.DL)
                                    .Nodes.Add("Design: " & Helper.ParseExactName(drn.DE))
                                End With
                            Next
                        End With
                        With .Nodes.Add("PET: " & item.PET.Name)
                            .Nodes.Add("ID: " & item.PET.PETID)
                            .Nodes.Add("HP: " & item.PET.HP)
                            .Nodes.Add("Level: " & item.PET.Level)
                            With .Nodes.Add("Locked Slots")
                                .Nodes.Add("Lasers: " & item.PET.LockedItems.Lasers)
                                .Nodes.Add("Generators: " & item.PET.LockedItems.Generators)
                                .Nodes.Add("Gears: " & item.PET.LockedItems.Gears)
                                .Nodes.Add("Protocols: " & item.PET.LockedItems.Protocols)
                            End With
                        End With
                        .Nodes.Add("Active: " & item.isActive)
                        .Nodes.Add("Selected: " & item.isSelected)
                        .Nodes.Add("Name: " & item.HangarName)
                    End With



                    '
                    ' Configurations
                    '

                    With .Nodes.Add("Configuration")

                        'First

                        With .Nodes.Add("1")

                            For Each member In MainJSON.Item("data").Item("ret").Item("hangars")
                                If member.Item("hangarID").ToString = item.HangarID Then

                                    'Ship

                                    For Each shipeq In member.Item("config").Item("1").Item("ship")
                                        With .Nodes.Add("Ship")
                                            If shipeq.Key = "EQ" Then
                                                For Each va In shipeq.Value
                                                    If va.Key = "lasers" Then
                                                        With .Nodes.Add("Lasers")
                                                            For Each lsr In va.Value
                                                                .Nodes.Add(Helper.GetNameByResourceID(lsr) & "(" & lsr & ")")
                                                            Next
                                                        End With
                                                    ElseIf va.Key = "generators" Then
                                                        With .Nodes.Add("Generators")
                                                            For Each gen In va.Value
                                                                .Nodes.Add(Helper.GetNameByResourceID(gen) & "(" & gen & ")")
                                                            Next
                                                        End With
                                                    ElseIf va.Key = "heavy_guns" Then
                                                        With .Nodes.Add("Heavy Guns")
                                                            For Each gun In va.Value
                                                                .Nodes.Add(Helper.GetNameByResourceID(gun) & "(" & gun & ")")
                                                            Next
                                                        End With
                                                    ElseIf va.Key = "extras" Then
                                                        With .Nodes.Add("Extras")
                                                            For Each ext In va.Value
                                                                .Nodes.Add(Helper.GetNameByResourceID(ext) & "(" & ext & ")")
                                                            Next
                                                        End With
                                                    End If
                                                Next
                                            End If
                                        End With
                                    Next

                                    'Drones
                                    With .Nodes.Add("Drones")
                                        If member.Item("config").Item("1").ContainsKey("drones") Then


                                            For Each droneeq In member.Item("config").Item("1").Item("drones")
                                                Dim drnName As String = ""
                                                For Each drn In item.Drones.Drones
                                                    If drn.ID = droneeq.Key Then
                                                        drnName = Helper.GetNameByL(drn.L)
                                                    End If
                                                Next
                                                With .Nodes.Add(drnName & "(" & droneeq.Key & ")")
                                                    For Each vs In droneeq.Value
                                                        If vs.Key = "EQ" Then
                                                            For Each va In droneeq.Value
                                                                For Each vr In va.Value
                                                                    Dim str As String = vr.Key.ToString
                                                                    If vr.Key = "default" Then
                                                                        With .Nodes.Add("Default")
                                                                            For Each lsr In vr.Value
                                                                                .Nodes.Add(Helper.GetNameByResourceID(lsr) & "(" & lsr & ")")
                                                                            Next
                                                                        End With
                                                                    ElseIf vr.Key = "design" Then
                                                                        With .Nodes.Add("Design")
                                                                            For Each lsr In vr.Value
                                                                                .Nodes.Add(Helper.GetNameByResourceID(lsr) & "(" & lsr & ")")
                                                                            Next
                                                                        End With
                                                                    End If
                                                                Next

                                                            Next
                                                        End If
                                                    Next

                                                End With
                                            Next
                                        End If
                                    End With

                                    'PET
                                    If member.Item("config").Item("1").ContainsKey("pet") Then
                                        For Each shipeq In member.Item("config").Item("1").Item("pet")
                                            With .Nodes.Add("PET")
                                                If shipeq.Key = "EQ" Then
                                                    For Each va In shipeq.Value
                                                        If va.Key = "lasers" Then
                                                            With .Nodes.Add("Lasers")
                                                                For Each lsr In va.Value
                                                                    .Nodes.Add(Helper.GetNameByResourceID(lsr) & "(" & lsr & ")")
                                                                Next
                                                            End With
                                                        ElseIf va.Key = "generators" Then
                                                            With .Nodes.Add("Generators")
                                                                For Each gen In va.Value
                                                                    .Nodes.Add(Helper.GetNameByResourceID(gen) & "(" & gen & ")")
                                                                Next
                                                            End With
                                                        ElseIf va.Key = "gears" Then
                                                            With .Nodes.Add("Gears")
                                                                For Each gun In va.Value
                                                                    .Nodes.Add(Helper.GetNameByResourceID(gun) & "(" & gun & ")")
                                                                Next
                                                            End With
                                                        ElseIf va.Key = "protocols" Then
                                                            With .Nodes.Add("Protocols")
                                                                For Each ext In va.Value
                                                                    .Nodes.Add(Helper.GetNameByResourceID(ext) & "(" & ext & ")")
                                                                Next
                                                            End With
                                                        End If
                                                    Next
                                                End If
                                            End With

                                        Next
                                    End If
                                End If
                            Next
                        End With

                        'Second

                        With .Nodes.Add("2")

                            For Each member In MainJSON.Item("data").Item("ret").Item("hangars")
                                If member.Item("hangarID").ToString = item.HangarID Then

                                    'Ship

                                    For Each shipeq In member.Item("config").Item("2").Item("ship")
                                        With .Nodes.Add("Ship")
                                            If shipeq.Key = "EQ" Then
                                                For Each va In shipeq.Value
                                                    If va.Key = "lasers" Then
                                                        With .Nodes.Add("Lasers")
                                                            For Each lsr In va.Value
                                                                .Nodes.Add(Helper.GetNameByResourceID(lsr) & "(" & lsr & ")")
                                                            Next
                                                        End With
                                                    ElseIf va.Key = "generators" Then
                                                        With .Nodes.Add("Generators")
                                                            For Each gen In va.Value
                                                                .Nodes.Add(Helper.GetNameByResourceID(gen) & "(" & gen & ")")
                                                            Next
                                                        End With
                                                    ElseIf va.Key = "heavy_guns" Then
                                                        With .Nodes.Add("Heavy Guns")
                                                            For Each gun In va.Value
                                                                .Nodes.Add(Helper.GetNameByResourceID(gun) & "(" & gun & ")")
                                                            Next
                                                        End With
                                                    ElseIf va.Key = "extras" Then
                                                        With .Nodes.Add("Extras")
                                                            For Each ext In va.Value
                                                                .Nodes.Add(Helper.GetNameByResourceID(ext) & "(" & ext & ")")
                                                            Next
                                                        End With
                                                    End If
                                                Next
                                            End If
                                        End With
                                    Next

                                    'Drones
                                    With .Nodes.Add("Drones")
                                        If member.Item("config").Item("1").ContainsKey("drones") Then
                                            For Each droneeq In member.Item("config").Item("2").Item("drones")
                                                Dim drnName As String = ""
                                                For Each drn In item.Drones.Drones
                                                    If drn.ID = droneeq.Key Then
                                                        drnName = Helper.GetNameByL(drn.L)
                                                    End If
                                                Next
                                                With .Nodes.Add(drnName & "(" & droneeq.Key & ")")
                                                    For Each vs In droneeq.Value
                                                        If vs.Key = "EQ" Then
                                                            For Each va In droneeq.Value
                                                                For Each vr In va.Value
                                                                    Dim str As String = vr.Key
                                                                    If vr.Key = "default" Then
                                                                        With .Nodes.Add("Default")
                                                                            For Each lsr In vr.Value
                                                                                .Nodes.Add(Helper.GetNameByResourceID(lsr) & "(" & lsr & ")")
                                                                            Next
                                                                        End With
                                                                    ElseIf vr.Key = "design" Then
                                                                        With .Nodes.Add("Desing")
                                                                            For Each lsr In vr.Value
                                                                                .Nodes.Add(Helper.GetNameByResourceID(lsr) & "(" & lsr & ")")
                                                                            Next
                                                                        End With
                                                                    End If
                                                                Next

                                                            Next
                                                        End If
                                                    Next

                                                End With
                                            Next
                                        End If
                                    End With

                                    'PET
                                    If member.Item("config").Item("1").ContainsKey("pet") Then
                                        For Each shipeq In member.Item("config").Item("2").Item("pet")
                                            With .Nodes.Add("PET")
                                                If shipeq.Key = "EQ" Then
                                                    For Each va In shipeq.Value
                                                        If va.Key = "lasers" Then
                                                            With .Nodes.Add("Lasers")
                                                                For Each lsr In va.Value
                                                                    .Nodes.Add(Helper.GetNameByResourceID(lsr) & "(" & lsr & ")")
                                                                Next
                                                            End With
                                                        ElseIf va.Key = "generators" Then
                                                            With .Nodes.Add("Generators")
                                                                For Each gen In va.Value
                                                                    .Nodes.Add(Helper.GetNameByResourceID(gen) & "(" & gen & ")")
                                                                Next
                                                            End With
                                                        ElseIf va.Key = "gears" Then
                                                            With .Nodes.Add("Gears")
                                                                For Each gun In va.Value
                                                                    .Nodes.Add(Helper.GetNameByResourceID(gun) & "(" & gun & ")")
                                                                Next
                                                            End With
                                                        ElseIf va.Key = "protocols" Then
                                                            With .Nodes.Add("Protocols")
                                                                For Each ext In va.Value
                                                                    .Nodes.Add(Helper.GetNameByResourceID(ext) & "(" & ext & ")")
                                                                Next
                                                            End With
                                                        End If
                                                    Next
                                                End If
                                            End With
                                        Next
                                    End If
                                End If
                            Next
                        End With
                    End With
                End With
            Next

        End With

        Logger.Log("Done!")
    End Sub

#End Region

#Region ">> DO Functions"

    'lasers
    'generators
    'extras
    'heavy_guns
    'design (drone)

    Sub UnEquip(ByVal cfg As Integer, ByVal type As String, ByVal item As String, ByVal hangarid As Integer)
        Try

            Dim postData As String = "{" & Chr(34) & "params" & Chr(34) & ":{" & Chr(34) & "hi" & Chr(34) & ":" & hangarid & "}," & Chr(34) & "from" & Chr(34) & ":{" & Chr(34) & "slotset" & Chr(34) & ":" & Chr(34) & type & Chr(34) & "," & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "ship" & Chr(34) & "," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "items" & Chr(34) & ":[" & Chr(34) & item & Chr(34) & "]}," & Chr(34) & "action" & Chr(34) & ":" & Chr(34) & "move" & Chr(34) & "," & Chr(34) & "to" & Chr(34) & ":{" & Chr(34) & "index" & Chr(34) & ":0," & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "inventory" & Chr(34) & "," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "}}"
            Dim enc As String = WebRPOST("http://" & txtServer.Text & ".darkorbit.bigpoint.com/flashAPI/inventory.php", "params=" & Crypter.Encode(postData) & "&action=move", cCook)
            Dim dec As String = Crypter.Decode(System.Web.HttpUtility.UrlDecode(enc))
            Dim tmpjson As Dictionary(Of String, Object)
            tmpjson = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(dec)
            If tmpjson.Item("isError").ToString <> "0" Then
                Logger.Log("Error while unequiping: " & tmpjson.Item("error").Item("message"))
            End If
        Catch ex As Exception
        End Try

    End Sub

    Sub Equip(ByVal cfg As Integer, ByVal type As String, ByVal item As String, ByVal hangarid As Integer)
        Try
            Dim postData As String = "{" & Chr(34) & "from" & Chr(34) & ":{" & Chr(34) & "configId" & Chr(34) & ":1," & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "inventory" & Chr(34) & "," & Chr(34) & "items" & Chr(34) & ":[" & Chr(34) & item & Chr(34) & "]}," & Chr(34) & "action" & Chr(34) & ":" & Chr(34) & "move" & Chr(34) & "," & Chr(34) & "to" & Chr(34) & ":{" & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "ship" & Chr(34) & "," & Chr(34) & "slotset" & Chr(34) & ":" & Chr(34) & type & Chr(34) & "}," & Chr(34) & "params" & Chr(34) & ":{" & Chr(34) & "hi" & Chr(34) & ":" & hangarid & "}}"
            Dim enc As String = WebRPOST("http://" & txtServer.Text & ".darkorbit.bigpoint.com/flashAPI/inventory.php", "params=" & Crypter.Encode(postData) & "&action=move", cCook)
            Dim dec As String = Crypter.Decode(System.Web.HttpUtility.UrlDecode(enc))
            Dim tmpjson As Dictionary(Of String, Object)
            tmpjson = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(dec)
            If tmpjson.Item("isError").ToString <> "0" Then
                Logger.Log("Error while equiping: " & tmpjson.Item("error").Item("message"))
            End If
        Catch ex As Exception
        End Try
    End Sub

    Sub EquipDrone(ByVal cfg As Integer, ByVal type As String, ByVal item As String, ByVal droneid As Integer, ByVal hangarid As Integer)
        Try
            Dim postData As String = "{" & Chr(34) & "params" & Chr(34) & ":{" & Chr(34) & "hi" & Chr(34) & ":" & hangarid & "}," & Chr(34) & "from" & Chr(34) & ":{" & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "inventory" & Chr(34) & "," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "items" & Chr(34) & ":[" & Chr(34) & item & Chr(34) & "]}," & Chr(34) & "action" & Chr(34) & ":" & Chr(34) & "move" & Chr(34) & "," & Chr(34) & "to" & Chr(34) & ":{" & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "drone" & Chr(34) & "," & Chr(34) & "droneId" & Chr(34) & ":" & Chr(34) & droneid & Chr(34) & "," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "slotset" & Chr(34) & ":" & Chr(34) & "default" & Chr(34) & "}}"
            If type = "design" Then
                postData = "{" & Chr(34) & "params" & Chr(34) & ":{" & Chr(34) & "hi" & Chr(34) & ":" & hangarid & "}," & Chr(34) & "from" & Chr(34) & ":{" & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "inventory" & Chr(34) & "," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "items" & Chr(34) & ":[" & Chr(34) & item & Chr(34) & "]}," & Chr(34) & "action" & Chr(34) & ":" & Chr(34) & "move" & Chr(34) & "," & Chr(34) & "to" & Chr(34) & ":{" & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "drone" & Chr(34) & "," & Chr(34) & "droneId" & Chr(34) & ":" & Chr(34) & droneid & Chr(34) & "," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "slotset" & Chr(34) & ":" & Chr(34) & "design" & Chr(34) & "}}"
            End If
            Dim enc As String = WebRPOST("http://" & txtServer.Text & ".darkorbit.bigpoint.com/flashAPI/inventory.php", "params=" & Crypter.Encode(postData) & "&action=move", cCook)
            Dim dec As String = Crypter.Decode(System.Web.HttpUtility.UrlDecode(enc))
            Dim tmpjson As Dictionary(Of String, Object)
            tmpjson = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(dec)
            If tmpjson.Item("isError").ToString <> "0" Then
                Logger.Log("Error while equiping: " & tmpjson.Item("error").Item("message"))
            End If
        Catch ex As Exception
        End Try
    End Sub

    Sub UnEquipDrone(ByVal cfg As Integer, ByVal type As String, ByVal item As String, ByVal droneid As Integer, ByVal hangarid As Integer)
        Try
            Dim postData As String = "{" & Chr(34) & "from" & Chr(34) & ":{" & Chr(34) & "droneId" & Chr(34) & ":" & Chr(34) & droneid & Chr(34) & "," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "drone" & Chr(34) & "," & Chr(34) & "slotset" & Chr(34) & ":" & Chr(34) & "default" & Chr(34) & "," & Chr(34) & "items" & Chr(34) & ":[" & Chr(34) & item & Chr(34) & "]}," & Chr(34) & "action" & Chr(34) & ":" & Chr(34) & "move" & Chr(34) & "," & Chr(34) & "to" & Chr(34) & ":{" & Chr(34) & "index" & Chr(34) & ":0," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "inventory" & Chr(34) & "}," & Chr(34) & "params" & Chr(34) & ":{" & Chr(34) & "hi" & Chr(34) & ":" & hangID & "}}"
            If type = "design" Then
                postData = "{" & Chr(34) & "from" & Chr(34) & ":{" & Chr(34) & "droneId" & Chr(34) & ":" & Chr(34) & droneid & Chr(34) & "," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "drone" & Chr(34) & "," & Chr(34) & "slotset" & Chr(34) & ":" & Chr(34) & "design" & Chr(34) & "," & Chr(34) & "items" & Chr(34) & ":[" & Chr(34) & item & Chr(34) & "]}," & Chr(34) & "action" & Chr(34) & ":" & Chr(34) & "move" & Chr(34) & "," & Chr(34) & "to" & Chr(34) & ":{" & Chr(34) & "index" & Chr(34) & ":0," & Chr(34) & "configId" & Chr(34) & ":" & cfg & "," & Chr(34) & "target" & Chr(34) & ":" & Chr(34) & "inventory" & Chr(34) & "}," & Chr(34) & "params" & Chr(34) & ":{" & Chr(34) & "hi" & Chr(34) & ":" & hangID & "}}"
            End If
            Dim enc As String = WebRPOST("http://" & txtServer.Text & ".darkorbit.bigpoint.com/flashAPI/inventory.php", "params=" & Crypter.Encode(postData) & "&action=move", cCook)
            Dim dec As String = Crypter.Decode(System.Web.HttpUtility.UrlDecode(enc))
            Dim tmpjson As Dictionary(Of String, Object)
            tmpjson = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(dec)
            If tmpjson.Item("isError").ToString <> "0" Then
                Logger.Log("Error while equiping: " & tmpjson.Item("error").Item("message"))
            End If
        Catch ex As Exception

        End Try
    End Sub

    Sub ClearConfig(ByVal hanggarID As Integer, ByVal CFG As Integer)
        Try
            Dim str As String = WebRPOST("http://" & txtServer.Text & ".darkorbit.bigpoint.com/flashAPI/inventory.php", "params=" & Crypter.Encode("{""configID"":" & CFG & ",""params"":{""hi"":" & hangID & "},""wipe"":1}") & "&action=clearConfig", cCook)
            Dim dec As String = Crypter.Decode(System.Web.HttpUtility.UrlDecode(str))
            Dim tmpjson As Dictionary(Of String, Object)
            tmpjson = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(dec)
            If tmpjson.Item("isError").ToString <> "0" Then
                Logger.Log("Error while cleaning config: " & tmpjson.Item("error").Item("message"))
            End If
        Catch ex As Exception

        End Try

    End Sub

    Sub ClearHangar(ByVal hangarid As Integer)
        Try
            ClearConfig(hangarid, 1)
            Thread.Sleep(100)
            ClearConfig(hangarid, 2)

        Catch ex As Exception

        End Try

    End Sub

    Sub EquipPet(ByVal cfg As Integer, ByVal type As String, ByVal item As String, ByVal hangarid As Integer)
        Try
            Dim postData As String = "{""params"":{""hi"":" & hangarid & "},""from"":{""target"":""inventory"",""configId"":" & cfg & ",""items"":[" & Chr(34) & item & Chr(34) & "]},""action"":""move"",""to"":{""target"":""pet"",""configId"":" & cfg & ",""slotset"":""" & type & """}}"
            Dim enc As String = WebRPOST("http://" & txtServer.Text & ".darkorbit.bigpoint.com/flashAPI/inventory.php", "params=" & Crypter.Encode(postData) & "&action=move", cCook)
            Dim dec As String = Crypter.Decode(System.Web.HttpUtility.UrlDecode(enc))
            Dim tmpjson As Dictionary(Of String, Object)
            tmpjson = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(dec)
            If tmpjson.Item("isError").ToString <> "0" Then
                Logger.Log("Error while equiping: " & tmpjson.Item("error").Item("message"))
            End If
        Catch ex As Exception

        End Try
    End Sub
#End Region

#Region ">> Load and Save Configurations"
    Function NewConfig() As Configuration
        Dim cfg As New Configuration
        cfg.First = New Configuration.CFG

        For i As Integer = 0 To 9
            cfg.First.Drones(i) = New Configuration.Drone
            cfg.First.Drones(i).Desing = ""
            cfg.First.Drones(i).Slot1 = ""
            cfg.First.Drones(i).Slot2 = ""
            cfg.First.Drones(i).ID = ""
        Next

        cfg.First.Ship = New Configuration.Ship
        cfg.First.Ship.Extras = New List(Of String)
        cfg.First.Ship.Generators = New List(Of String)
        cfg.First.Ship.Heavy_Guns = New List(Of String)
        cfg.First.Ship.Lasers = New List(Of String)

        cfg.First.PET = New Configuration.PET
        cfg.First.PET.Gears = New List(Of String)
        cfg.First.PET.Generators = New List(Of String)
        cfg.First.PET.Lasers = New List(Of String)
        cfg.First.PET.Protocols = New List(Of String)

        cfg.Second = New Configuration.CFG

        For i As Integer = 0 To 9
            cfg.Second.Drones(i) = New Configuration.Drone
            cfg.Second.Drones(i).Desing = ""
            cfg.Second.Drones(i).Slot1 = ""
            cfg.Second.Drones(i).Slot2 = ""
            cfg.Second.Drones(i).ID = ""
        Next

        cfg.Second.Ship = New Configuration.Ship
        cfg.Second.Ship.Extras = New List(Of String)
        cfg.Second.Ship.Generators = New List(Of String)
        cfg.Second.Ship.Heavy_Guns = New List(Of String)
        cfg.Second.Ship.Lasers = New List(Of String)

        cfg.Second.PET = New Configuration.PET
        cfg.Second.PET.Gears = New List(Of String)
        cfg.Second.PET.Generators = New List(Of String)
        cfg.Second.PET.Lasers = New List(Of String)
        cfg.Second.PET.Protocols = New List(Of String)

        Return cfg
    End Function

    Function ReadConfiguration(ByVal path As String) As Configuration
        Dim tmp As Configuration = NewConfig()

        Dim xs As New XmlSerializer(tmp.GetType)
        Dim fs As New System.IO.StreamReader(path)
        tmp = DirectCast(xs.Deserialize(fs), Configuration)
        fs.Close()
        Logger.Log("Successfull loaded configfile!")
        Return tmp
    End Function

    Function SaveConfiguration(ByVal path As String, ByVal cfg As Configuration) As Boolean
        Try
            Dim fs As New System.IO.StreamWriter(path)
            Dim xs As New XmlSerializer(cfg.GetType)
            xs.Serialize(fs, cfg)
            fs.Close()
            Logger.Log("Successfull saved configfile!")
            Return True
        Catch ex As Exception
            Logger.Log("Error while saving configfile!")
            Return False
        End Try

    End Function

    Private Sub cmdSaveConfiguration_Click(sender As Object, e As EventArgs) Handles cmdSaveConfiguration.Click
        Dim cfg As Configuration = NewConfig()
        For Each member In MainJSON.Item("data").Item("ret").Item("hangars")
            If member.Item("hangarID").ToString = hangID Then

                For Each shipeq In member.Item("config").Item("1").Item("ship")
                    If shipeq.Key = "EQ" Then
                        For Each va In shipeq.Value
                            If va.Key = "lasers" Then
                                For Each lsr In va.Value
                                    cfg.First.Ship.Lasers.Add(lsr)
                                Next
                            ElseIf va.Key = "generators" Then
                                For Each gen In va.Value
                                    cfg.First.Ship.Generators.Add(gen)
                                Next
                            ElseIf va.Key = "heavy_guns" Then
                                For Each gun In va.Value
                                    cfg.First.Ship.Heavy_Guns.Add(gun)
                                Next
                            ElseIf va.Key = "extras" Then
                                For Each ext In va.Value
                                    cfg.First.Ship.Extras.Add(ext)
                                Next
                            End If
                        Next
                    End If
                Next

                'Drones
                If member.Item("config").Item("1").ContainsKey("drones") Then
                    Dim drnIndex As Integer = 0
                    For Each drn In member.Item("config").Item("1").Item("drones")
                        cfg.First.Drones(drnIndex).ID = drn.Key
                        For Each vs In drn.Value
                            If vs.Key = "EQ" Then
                                For Each va In drn.Value
                                    For Each vr In va.Value
                                        Dim str As String = vr.Key
                                        If vr.Key = "default" Then
                                            For Each lsr In vr.Value
                                                If cfg.First.Drones(drnIndex).Slot1 = "" Then
                                                    cfg.First.Drones(drnIndex).Slot1 = lsr
                                                Else
                                                    cfg.First.Drones(drnIndex).Slot2 = lsr
                                                End If
                                            Next
                                        ElseIf vr.Key = "design" Then
                                            For Each lsr In vr.Value
                                                cfg.First.Drones(drnIndex).Desing = lsr
                                            Next

                                        End If
                                    Next

                                Next
                            End If
                        Next
                        drnIndex += 1
                    Next
                End If

                If member.Item("config").Item("1").ContainsKey("pet") Then
                    For Each drn In member.Item("config").Item("1").Item("pet")
                        If drn.Key = "EQ" Then
                            For Each mbr In drn.Value
                                If mbr.Key = "lasers" Then

                                    For Each lsr In mbr.Value
                                        cfg.First.PET.Lasers.Add(lsr)
                                    Next
                                ElseIf mbr.Key = "generators" Then
                                    For Each lsr In mbr.Value
                                        cfg.First.PET.Generators.Add(lsr)
                                    Next
                                ElseIf mbr.Key = "gears" Then
                                    For Each lsr In mbr.Value
                                        cfg.First.PET.Gears.Add(lsr)
                                    Next
                                ElseIf mbr.Key = "protocols" Then
                                    For Each lsr In mbr.Value
                                        cfg.First.PET.Protocols.Add(lsr)
                                    Next
                                End If
                            Next
                        End If
                    Next
                End If
            End If
        Next
        'Second



        For Each member In MainJSON.Item("data").Item("ret").Item("hangars")
            If member.Item("hangarID").ToString = hangID Then

                'Ship

                For Each shipeq In member.Item("config").Item("2").Item("ship")
                    If shipeq.Key = "EQ" Then
                        For Each va In shipeq.Value
                            If va.Key = "lasers" Then

                                For Each lsr In va.Value
                                    cfg.Second.Ship.Lasers.Add(lsr)
                                Next
                            ElseIf va.Key = "generators" Then
                                For Each gen In va.Value
                                    cfg.Second.Ship.Generators.Add(gen)
                                Next
                            ElseIf va.Key = "heavy_guns" Then
                                For Each gun In va.Value
                                    cfg.Second.Ship.Heavy_Guns.Add(gun)
                                Next
                            ElseIf va.Key = "extras" Then
                                For Each ext In va.Value
                                    cfg.Second.Ship.Extras.Add(ext)
                                Next
                            End If
                        Next
                    End If
                Next

                'Drones
                If member.Item("config").Item("2").ContainsKey("drones") Then
                    Dim drnIndex As Integer = 0
                    For Each droneeq In member.Item("config").Item("2").Item("drones")
                        cfg.Second.Drones(drnIndex).ID = droneeq.Key
                        For Each vs In droneeq.Value
                            If vs.Key = "EQ" Then
                                For Each va In droneeq.Value
                                    For Each vr In va.Value
                                        Dim str As String = vr.Key
                                        If vr.Key = "default" Then
                                            For Each lsr In vr.Value
                                                If cfg.Second.Drones(drnIndex).Slot1 = "" Then
                                                    cfg.Second.Drones(drnIndex).Slot1 = lsr
                                                Else
                                                    cfg.Second.Drones(drnIndex).Slot2 = lsr
                                                End If
                                            Next
                                        ElseIf vr.Key = "design" Then
                                            For Each lsr In vr.Value
                                                cfg.Second.Drones(drnIndex).Desing = lsr
                                            Next
                                        End If
                                    Next

                                Next
                            End If
                        Next
                        drnIndex += 1
                    Next
                End If
                If member.Item("config").Item("2").ContainsKey("pet") Then
                    For Each drn In member.Item("config").Item("2").Item("pet")
                        If drn.Key = "EQ" Then
                            For Each mbr In drn.Value
                                If mbr.Key = "lasers" Then

                                    For Each lsr In mbr.Value
                                        cfg.Second.PET.Lasers.Add(lsr)
                                    Next
                                ElseIf mbr.Key = "generators" Then
                                    For Each lsr In mbr.Value
                                        cfg.Second.PET.Generators.Add(lsr)
                                    Next
                                ElseIf mbr.Key = "gears" Then
                                    For Each lsr In mbr.Value
                                        cfg.Second.PET.Gears.Add(lsr)
                                    Next
                                ElseIf mbr.Key = "protocols" Then
                                    For Each lsr In mbr.Value
                                        cfg.Second.PET.Protocols.Add(lsr)
                                    Next
                                End If
                            Next
                        End If
                    Next
                End If
            End If
        Next
        With New SaveFileDialog
            .FileName = ""
            .Filter = "XML|*.xml"


            Dim b As Boolean = False
            Invoke(Sub() If .ShowDialog = Windows.Forms.DialogResult.OK Then b = True)

            If b Then
                SaveConfiguration(.FileName, cfg)
            End If
        End With
    End Sub

#End Region

#Region ">> Change Configuration"
    Private Sub cmdChangeConfiguration_Click(sender As Object, e As EventArgs) Handles cmdChangeConfiguration.Click
        Dim cfg As Configuration = NewConfig()

        With New OpenFileDialog
            .FileName = ""
            .Multiselect = False
            .Filter = "XML|*.xml"
            Dim ok As Boolean = False

            If .ShowDialog = Windows.Forms.DialogResult.OK Then
                cmdChangeConfiguration.Enabled = False
                cmdLogToHangar.Enabled = False
                cmdSaveConfiguration.Enabled = False
                cmbHangars.Enabled = False




                cfg = ReadConfiguration(.FileName)
                With New Thread(New ParameterizedThreadStart(AddressOf DoChange))
                    .IsBackground = True
                    .Start(cfg)
                End With

            End If
        End With

    End Sub

    Sub DoChange(ByVal config As Configuration)
        Dim sw As New Stopwatch
        sw.Start()
        ' if an async method doesn't have await inside it
        ' it doesn't work async

        ' it is still a normal method
        ' use Await Task.Run(
        'How can i give argument to this?
        ' takes an Action as an argument
        'Await ClearHangar(hangID)
        'yepsub
        Logger.Log("Changing started!")
        ClearHangar(hangID)
        Logger.Log("Cleaned hangar #" & hangID & "!")
        'lasers
        'generators
        'extras
        'heavy_guns
        'design (drone)


        'First CFG 
        Thread.Sleep(100)
        If config.First.Ship.Lasers.Count > 0 Then
            Equip(1, "lasers", Helper.ParseListToItemarray(config.First.Ship.Lasers), hangID)
            Logger.Log("Equipped lasers to ship configuration 1")
            Thread.Sleep(50)
        End If
        If config.First.Ship.Heavy_Guns.Count > 0 Then
            Equip(1, "heavy_guns", Helper.ParseListToItemarray(config.First.Ship.Heavy_Guns), hangID)
            Logger.Log("Equipped heavyguns to ship configuration 1")
            Thread.Sleep(50)
        End If
        If config.First.Ship.Generators.Count > 0 Then
            Equip(1, "generators", Helper.ParseListToItemarray(config.First.Ship.Generators), hangID)
            Logger.Log("Equipped generators to ship configuration 1")
            Thread.Sleep(50)
        End If
        If config.First.Ship.Extras.Count > 0 Then
            Equip(1, "extras", Helper.ParseListToItemarray(config.First.Ship.Extras), hangID)
            Logger.Log("Equipped extras to ship configuration 1")
            Thread.Sleep(50)
        End If
        Thread.Sleep(500)

        For Each drn In config.First.Drones
            If drn.ID <> "" Then
                If drn.Slot1.Trim <> "" Then
                    Dim type As String = Helper.GetTypeByResourceID(CInt(drn.Slot1))
                    If type = "Weapon_LaserType" Then
                        EquipDrone(1, "laser", drn.Slot1, CInt(drn.ID), hangID)
                    ElseIf type = "Generator_ShieldType" OrElse type = "Generator_EngineType" Then
                        EquipDrone(1, "generators", drn.Slot1, CInt(drn.ID), hangID)
                    ElseIf type = "Extra_ExtraType" Then
                        EquipDrone(1, "extras", drn.Slot1, CInt(drn.ID), hangID)
                    End If
                    Thread.Sleep(500)
                End If

                If drn.Slot2.Trim <> "" Then
                    Dim type As String = Helper.GetTypeByResourceID(CInt(drn.Slot2))
                    If type = "Weapon_LaserType" Then
                        EquipDrone(1, "laser", drn.Slot2, CInt(drn.ID), hangID)
                    ElseIf type = "Generator_ShieldType" OrElse type = "Generator_EngineType" Then
                        EquipDrone(1, "generators", drn.Slot2, CInt(drn.ID), hangID)
                    ElseIf type = "Extra_ExtraType" Then
                        EquipDrone(1, "extras", drn.Slot2, CInt(drn.ID), hangID)
                    End If
                    Thread.Sleep(500)
                End If
                If drn.Desing <> "" Then
                    EquipDrone(1, "design", drn.Desing, CInt(drn.ID), hangID)
                End If
                Logger.Log("Equipped drone " & drn.ID & " in configuration 1")
            End If
        Next
        If config.First.PET.Lasers.Count > 0 Then
            EquipPet(1, "lasers", Helper.ParseListToItemarray(config.First.PET.Lasers), hangID)
            Thread.Sleep(50)
        End If
        If config.First.PET.Generators.Count > 0 Then
            EquipPet(1, "generators", Helper.ParseListToItemarray(config.First.PET.Generators), hangID)
            Thread.Sleep(50)
        End If
        If config.First.PET.Gears.Count > 0 Then
            EquipPet(1, "gears", Helper.ParseListToItemarray(config.First.PET.Gears), hangID)
            Thread.Sleep(50)
        End If
        If config.First.PET.Protocols.Count > 0 Then
            EquipPet(1, "protocols", Helper.ParseListToItemarray(config.First.PET.Protocols), hangID)
            Thread.Sleep(50)
        End If
        Thread.Sleep(500)
        Logger.Log("Euipped PET in configuration 1")

        'Second CFG 
        If config.Second.Ship.Lasers.Count > 0 Then
            Equip(2, "lasers", Helper.ParseListToItemarray(config.Second.Ship.Lasers), hangID)
            Logger.Log("Equipped lasers to ship configuration 1")
            Thread.Sleep(50)
        End If
        If config.Second.Ship.Heavy_Guns.Count > 0 Then
            Equip(2, "heavy_guns", Helper.ParseListToItemarray(config.Second.Ship.Heavy_Guns), hangID)
            Logger.Log("Equipped heavyguns to ship configuration 1")
            Thread.Sleep(50)
        End If
        If config.Second.Ship.Generators.Count > 0 Then
            Equip(2, "generators", Helper.ParseListToItemarray(config.Second.Ship.Generators), hangID)
            Logger.Log("Equipped generators to ship configuration 1")
            Thread.Sleep(50)
        End If
        If config.Second.Ship.Extras.Count > 0 Then
            Equip(2, "extras", Helper.ParseListToItemarray(config.Second.Ship.Extras), hangID)
            Logger.Log("Equipped extras to ship configuration 1")
            Thread.Sleep(50)
        End If
        Thread.Sleep(500)

        For Each drn In config.Second.Drones
            If drn.ID <> "" Then
                If drn.Slot1.Trim <> "" Then
                    Dim type As String = Helper.GetTypeByResourceID(CInt(drn.Slot1))
                    If type = "Weapon_LaserType" Then
                        EquipDrone(2, "laser", drn.Slot1, CInt(drn.ID), hangID)
                    ElseIf type = "Generator_ShieldType" OrElse type = "Generator_EngineType" Then
                        EquipDrone(2, "generators", drn.Slot1, CInt(drn.ID), hangID)
                    ElseIf type = "Extra_ExtraType" Then
                        EquipDrone(2, "extras", drn.Slot1, CInt(drn.ID), hangID)
                    End If
                    Thread.Sleep(500)
                End If
                If drn.Slot2.Trim <> "" Then
                    Dim type As String = Helper.GetTypeByResourceID(CInt(drn.Slot2))
                    If type = "Weapon_LaserType" Then
                        EquipDrone(2, "laser", drn.Slot2, CInt(drn.ID), hangID)
                    ElseIf type = "Generator_ShieldType" OrElse type = "Generator_EngineType" Then
                        EquipDrone(2, "generators", drn.Slot2, CInt(drn.ID), hangID)
                    ElseIf type = "Extra_ExtraType" Then
                        EquipDrone(2, "extras", drn.Slot2, CInt(drn.ID), hangID)
                    End If
                    Thread.Sleep(500)
                End If
                If drn.Desing <> "" Then
                    EquipDrone(2, "design", drn.Desing, CInt(drn.ID), hangID)
                End If
                Logger.Log("Equipped drone " & drn.ID & " in configuration 2")
            End If
        Next
        Thread.Sleep(500)

        If config.Second.PET.Lasers.Count > 0 Then
            EquipPet(2, "lasers", Helper.ParseListToItemarray(config.Second.PET.Lasers), hangID)
            Thread.Sleep(50)
        End If
        If config.Second.PET.Generators.Count > 0 Then
            EquipPet(2, "generators", Helper.ParseListToItemarray(config.Second.PET.Generators), hangID)
            Thread.Sleep(50)
        End If
        If config.Second.PET.Gears.Count > 0 Then
            EquipPet(2, "gears", Helper.ParseListToItemarray(config.Second.PET.Gears), hangID)
            Thread.Sleep(50)
        End If
        If config.Second.PET.Protocols.Count > 0 Then
            EquipPet(2, "protocols", Helper.ParseListToItemarray(config.Second.PET.Protocols), hangID)
            Thread.Sleep(50)
        End If
        Thread.Sleep(500)
        Logger.Log("Euipped PET in configuration 2")
        sw.Stop()
        Dim str As String = sw.Elapsed.Minutes & ":" & sw.Elapsed.Seconds
        Logger.Log("Done! Changing took " & str & "!")

        bDecrypted = Crypter.Decode(WebRPOST("http://" & txtServer.Text & ".darkorbit.bigpoint.com/flashAPI/inventory.php", "params=" & Crypter.Encode("{" & Chr(34) & "nr" & Chr(34) & ":1}") & "&action=init", cCook))
        MainJSON = jsonSerializer.Deserialize(Of Dictionary(Of String, Object))(bDecrypted)
        If CStr(MainJSON.Item("isError")) <> "0" Then
            MsgBox("Error from darkorbit: " & MainJSON.Item("error").Item("message"))
            Application.Exit()
        End If
        Helper = New Helper(MainJSON)
        For Each hangar In MainJSON.Item("data").Item("ret").Item("hangars")
            Invoke(Sub() cmbHangars.Items.Add(hangar.Item("hangarID") & "(" & Helper.ParseExactName(hangar.Item("general").Item("ship").Item("SM")) & ")"))
        Next
        Invoke(Sub() cmbHangars.SelectedIndex = 0)

        Invoke(Sub()
                   cmdChangeConfiguration.Enabled = True
                   cmdLogToHangar.Enabled = True
                   cmdSaveConfiguration.Enabled = True
                   cmbHangars.Enabled = True
               End Sub)
    End Sub
#End Region

#Region ">> Save & Load Data"
    Private Sub frmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        Application.ExitThread()
        Application.Exit()
    End Sub

    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        SavedData = New List(Of SavedData)
        If My.Settings.Settings.Count > 0 Then
            For Each D In My.Settings.Settings
                Dim s As New SavedData
                s.Username = D.Split(":c")(0)
                s.Password = D.Split(":c")(1)
                s.Server = D.Split(":c")(2)
                SavedData.Add(s)
            Next
            For Each item In SavedData
                txtUsername.Items.Add(item.Username)
            Next
            txtUsername.SelectedIndex = 0
        End If

        Dim str As String = New WebClient().DownloadString("http://www.elitepvpers.com/forum/darkorbit/2677402-release-darkorbit-configuration-manager-heaven.html")
        Dim vers = GetBetween(str, "Current version: ", "<br />")

        If vers > Application.ProductVersion Then
            If MessageBox.Show("Do you want to download version " & vers & " now?", "New version is avaible!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                Process.Start("http://www.elitepvpers.com/forum/darkorbit/2677402-release-darkorbit-configuration-manager-heaven.html")
                Application.Exit()
            End If
        End If
    End Sub


    Private Sub cmdDelete_Click(sender As Object, e As EventArgs) Handles cmdDelete.Click
        Try
            Dim ind As Integer = txtUsername.SelectedIndex
            txtUsername.Items.RemoveAt(ind)
            txtUsername.Text = ""
            txtPassword.Text = ""
            txtServer.Text = ""
            My.Settings.Settings.RemoveAt(ind)
            My.Settings.Save()
        Catch ex As Exception

        End Try

    End Sub
#End Region

    Private Sub cmdOpenWebbrowser_Click(sender As Object, e As EventArgs) Handles cmdOpenWebbrowser.Click
        Process.Start("http://" & txtServer.Text & ".darkorbit.bigpoint.com/indexInternal.es?action=internalDock&tpl=internalDockEquipment&dosid=" & SessionID)
    End Sub

    Private Sub txtUsername_SelectedIndexChanged(sender As Object, e As EventArgs) Handles txtUsername.SelectedIndexChanged
        txtPassword.Text = SavedData(txtUsername.SelectedIndex).Password
        txtUsername.Text = SavedData(txtUsername.SelectedIndex).Username
        txtServer.Text = SavedData(txtUsername.SelectedIndex).Server
    End Sub
End Class
